package cn.gok.springboot.controller;

import cn.gok.springboot.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author 陈少华
 * @create 2022-07-14 15:11
 **/

@RestController
@Controller
@RequestMapping("/user") //通常是实体类的小写
public class UserController {
    @Autowired
    private User user;
    ModelAndView md=new ModelAndView();
    List<User> list=new ArrayList<>();

    @RequestMapping("/findOne")
    public  ModelAndView findOne(){
//        新建模型和视图对象
//        新建用户对象，通过构造进行赋值
//        使用set进行赋值
        user.setAge(20);
        user.setName("小白");
        user.setPassword("123654");
//        attributeName:属性名
        md.addObject("users",user);//传递数据
        md.setViewName("user");
        return  md;
    }

//    @RequestMapping("/findOne")
//    public  String findOne(Model model){
////        model模型存放数据
//        user.setAge(30);
//        user.setName("中白");
//        user.setPassword("123654");
//        model.addAttribute("users",user);
//        return "user";
//    }

    @RequestMapping("/findAll")
    public  ModelAndView findAll(){
        User user1=new User(19,"zs","123456");
        User user2=new User(20,"ls","123456");
        User user3=new User(21,"ww","123456");
        User user4=new User(23,"ll","123456");
        Collections.addAll(list,user1,user2,user3,user4);
        System.out.println(list);
        md.addObject("list",list);
        md.setViewName("userlist");
        return md;
    }

    @RequestMapping("/del")
    public  String delUser(@RequestParam int age){//@RequestParam请求参数
//        用户存储list里面，遍历，get(i).getage()==this.age，拿到对应的用户
        for (int i=0;i<list.size();i++){
            if (list.get(i).getAge()==age)
                list.remove(i);//i是用户对象的索引
            System.out.println(list);
            return "删除成功";
        }
        return "删除失败";
    }
}
